package run.yiqi.blog.controller;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

@Slf4j
@Controller
public class ReportController {

    @Lazy @Resource private DataSource dataSource;
    @Lazy @Autowired private HttpServletRequest request;
    @Lazy @Autowired private HttpServletResponse response;

    @SneakyThrows
    @ResponseBody
    @RequestMapping(value = { "/report/issueReport" }, method = RequestMethod.GET)
    public void issueReport() {
        log.info("/report/issueReport");

        ClassPathResource resource = new ClassPathResource("reports" + File.separator + "issueReport.jasper");
        @Cleanup
        InputStream jasperStream = resource.getInputStream();

        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
        
        @Cleanup
        Connection conn = dataSource.getConnection();
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline;");
        
        @Cleanup
        OutputStream outputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
        
    }

    
}